package com.lengyu.iottransfer.gateway.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lengyu.iottransfer.gateway.common.ByteUtils;
import com.lengyu.iottransfer.gateway.config.MqttSendGateway;
import com.lengyu.iottransfer.gateway.entity.DeviceTransfer;
import com.lengyu.iottransfer.gateway.redis.RedisUtils;
import com.lengyu.iottransfer.gateway.service.IDeviceTransferService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

@Service
public class ElecLcdTransferService {
    private static final Logger logger = LoggerFactory.getLogger(ElecLcdTransferService.class);
    @Resource
    private MqttSendGateway mqttSendGateway;

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    IDeviceTransferService deviceTransferService;
    
    @Async // 声明异步方法
    public void  decodeData(byte[] payLoad,String topic) {
        int cmd = payLoad[1] & 0xFF;
        int numCount = payLoad[2] & 0xFF;
        //校验第一、第二字节
        if(cmd == 3){
            //正常
            if(numCount == 4){
                String code = topic.split("/")[2] + "MN" + ByteUtils.byteToHex(payLoad[0]);

                DeviceTransfer deviceTransfer = deviceTransferService.getDeviceTransferByCode(code);

                if(deviceTransfer == null){
                    logger.info("无此设备配置信息：" + code);
                    return;
                }
                //正向有功电能
                long data2 = ByteUtils.byteArrayToUnsignedLong(payLoad,3);
                BigDecimal positiveActiveEnergy = BigDecimal.valueOf(data2).divide(BigDecimal.valueOf(100),2,RoundingMode.HALF_UP);

                positiveActiveEnergy =  (positiveActiveEnergy.multiply(deviceTransfer.getElecMultiply())).add(deviceTransfer.getBaseValue());

                JSONObject json = new JSONObject();
                JSONObject paramJson = new JSONObject();
                paramJson.put("positiveActiveEnergy",positiveActiveEnergy);
                json.put("id",System.currentTimeMillis());
                json.put("method","thing.event.property.post");
                json.put("params",paramJson);

                if(deviceTransfer != null){
                    //发送消息到IITA平台

                    checkConnectFlag(deviceTransfer);
                    mqttSendGateway.sendToMqtt(deviceTransferService.getThirdPlatPostPropertyTopic(deviceTransfer), json.toJSONString());

                    //发送消息到自己平台
                    mqttSendGateway.sendToMqtt(deviceTransferService.getIotPlatPropertyTopic(deviceTransfer), json.toJSONString());
                }

            }
        }
        else{

        }

        //获取数据字节长度
    }

    /**
     *
     * @param deviceTransfer
     * clientId = productKey_deviceName_model
     */
    public void checkConnectFlag( DeviceTransfer deviceTransfer) {
        JSONObject json = new JSONObject();
        String clientId = deviceTransferService.getClientIdForIITA(deviceTransfer);
        json.put("clientid",clientId);
//        logger.info("发送设备连接信息：" + json.toJSONString());
        mqttSendGateway.sendToMqtt("/sys/client/connected", json.toJSONString());
    }


    /**
     * 发送到电表的读取命令
     * //地址码+ 功能码+数据码+校验码
     * @return
     */
    public String getHexSendInfo2(){

        StringBuilder sb = new StringBuilder();
        //设备地址 1-124之间
        sb.append("01").append(" ");
        //功能码03
        sb.append("03").append(" ");

        //数据码---start
        //寄存器地址高位
        sb.append("10").append(" ");
        //寄存器地址低位
        sb.append("3D").append(" ");

        //寄存器个数高位
        sb.append("00").append(" ");
        //寄存器个数低位
        sb.append("04").append(" ");
        //数据码---end
        //校验码---start
        //CRC16 低位
        sb.append("10").append(" ");
        //CRC16 高位
        sb.append("00").append(" ");
        //校验码---end
        return sb.toString();
    }
}
